import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/utils/data_util.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/widgets/app_btn.dart';

/// 选择成色
class SelectQuality extends StatefulWidget {
  const SelectQuality({
    Key? key,
    this.onSelected,
    this.initSelect,
  }) : super(key: key);

  @override
  _SelectQualityState createState() => _SelectQualityState();

  final String? initSelect;
  final Function(String?)? onSelected;
}

class _SelectQualityState extends State<SelectQuality> with SafeState<SelectQuality> {
  String? _select;

  @override
  void initState() {
    super.initState();
    _select = widget.initSelect;
  }

  /// 选择
  Future<void> _tap(String k) async {
    if (k != _select) {
      safeSetState(() => _select = k);
      widget.onSelected?.call(_select);
    }
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 40,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.zero,
        itemCount: qualities.length,
        itemBuilder: (_, int index) => _buildItem(index),
      ),
    );
  }

  /// 构建项
  Widget _buildItem(int i) {
    final String k = qualities.keys.toList()[i];
    final String v = qualities.values.toList()[i];
    return Padding(
      padding: const EdgeInsets.only(right: 6),
      child: AppBtn(
        onTap: () async => await _tap(k),
        alignment: Alignment.center,
        color: k == _select ? theme(context) : theme(context).withOpacity(0.1),
        text: v,
        textStyle: TextStyle(
          fontSize: 13,
          color: k == _select ? white(context) : theme(context),
        ),
      ),
    );
  }
}
